package com.huaao.micropolice.root.controllers.system;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.gson.Gson;
import com.huaao.micropolice.common.util.JsonUtil;
import com.huaao.micropolice.core.common.gson.GsonSimpleFilter;
import com.huaao.micropolice.core.common.page.Page;
import com.huaao.micropolice.core.model.system.Button;
import com.huaao.micropolice.core.model.system.Menu;
import com.huaao.micropolice.core.service.system.ButtonService;
import com.huaao.micropolice.root.controllers.BaseController;

@Controller
@RequestMapping("system/button")
public class ButtonController extends BaseController{
	
	@Autowired
	private ButtonService buttonService;
	
	@RequestMapping("index.do")
	public String index(){
		return "/system/button/index";
	}
	
	@RequestMapping("list.do")
    public ResponseEntity<String> list() {
		String json = "";
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			Page page = getPage();
			buttonService.list(getSort(),page);
			map.put("total", page.getTotalPageNum());
			map.put("page", page.getPageNum());
			map.put("records", page.getTotalCount());
			map.put("rows",page.getResults());
			Gson gson = new GsonSimpleFilter().createBuilder()
	                .setFilterClass(Button.class).setClassIncludes("id").setClassIncludes("name").setClassIncludes("permission").setClassIncludes("menu")
	                .setFilterClass(Menu.class).setClassIncludes("id").setClassIncludes("name")
	                .buildPreFilter()
	                .create();
			json = gson.toJson(map);
		} catch (Exception e) {
			json = JsonUtil.toJson(failMap());
		}
		return super.ajaxModel(JSON, json);
    }
	
	
	
	@RequestMapping("save.do")
	public ResponseEntity<String> save(Button button){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if(StringUtils.isBlank(button.getId())){
				buttonService.add(button);
			}else{
				buttonService.edit(button);
			}
			map = successMap();
		} catch (Exception e) {
			map = failMap();
		}
		return super.ajaxModel(JSON, JsonUtil.toJson(map));
	}
	
	@RequestMapping("dels.do")
	public ResponseEntity<String> dels(@RequestParam(value = "ids[]") String[] ids){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			buttonService.dels(ids);
			map = successMap();
		} catch (Exception e) {
			map = failMap();
		}
		return super.ajaxModel(JSON, JsonUtil.toJson(map));
	}
}
